import bigInt from "big-integer";

export function handlePublicKey(key) {
  const a = key.split("|");
  const a2 = _base64ToArrayBuffer(a[1]);
  const a3 = bigInt.fromArray(a2.reverse(), 256);
  return a3;
}

function _base64ToArrayBuffer(base64) {
  const binary_string = window.atob(base64);

  const len = binary_string.length;

  const bytes = [];

  for (let i = 0; i < len; i++) {
    bytes[i] = bigInt(binary_string.charCodeAt(i));
  }
  return bytes;
}

export function arrayBufferToBase64(buffer) {
  let binary = "";
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

export function strToUtf8Bytes(text) {
  const code = encodeURIComponent(text);
  const bytes = [];
  for (let i = 0; i < code.length; i++) {
    const c = code.charAt(i);
    if (c === "%") {
      const hex = code.charAt(i + 1) + code.charAt(i + 2);
      const hexval = parseInt(hex, 16);
      bytes.push(hexval);
      i += 2;
    } else {
      bytes.push(c.charCodeAt(0));
    }
  }
  return bytes;
}
